import axios from 'axios'
import type {
  AxiosInstance,
  InternalAxiosRequestConfig,
  AxiosRequestConfig,
  AxiosResponse,
} from 'axios'
import { useUserStore } from '@/stores/user'

// 定义通用响应类型
export interface ApiResponse<T = unknown> {
  success: boolean
  message?: string
  data?: T
}

const instance: AxiosInstance = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 5000,
})

// 请求拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStore()
    const token = userStore.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }

    // 添加时间戳参数防止缓存（对GET请求）
    if (config.method?.toLowerCase() === 'get') {
      config.params = config.params || {}
      // 添加时间戳
      config.params._t = new Date().getTime()
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    const userStore = useUserStore()
    // 如果返回的headers中包含新的token，则更新
    const newToken = response.headers['authorization']
    if (newToken) {
      userStore.setToken(newToken.replace('Bearer ', ''))
    }

    // 确保响应包含必要的字段
    const data = response.data
    if (data && typeof data === 'object' && !('success' in data)) {
      return {
        success: response.status >= 200 && response.status < 300,
        message: '',
        data: data,
      }
    }

    return data
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      // 未授权，清除token并重定向到登录页
      const userStore = useUserStore()
      userStore.logout()
      window.location.href = '/login'
    }
    return Promise.reject(error)
  },
)

export default function request<T = unknown>(config: AxiosRequestConfig): Promise<ApiResponse<T>> {
  return instance(config) as Promise<ApiResponse<T>>
}
